import Mn from 'backbone.marionette';
import { ajax_call } from '../../tools.js';
import { getPercent } from '../../math.js';
import NodeFileCollection from '../../common/models/NodeFileCollection.js';
import TotalModel from '../models/TotalModel.js';
import SupplierInvoiceModel from '../models/SupplierInvoiceModel.js';
import SupplierInvoiceLineCollection from '../models/SupplierInvoiceLineCollection.js';
import FacadeModelApiMixin from "../../base/components/FacadeModelApiMixin";
import StatusLogEntryCollection
    from "../../common/models/StatusLogEntryCollection";


const FacadeClass = Mn.Object.extend(FacadeModelApiMixin).extend({
    radioEvents: {
        "changed:line": "computeLineTotal",
        "changed:totals": "computeFundingTotals",
    },
    radioRequests: {
        'get:collection': 'getCollectionRequest',
        'get:totalmodel': 'getTotalModelRequest',
        'get:model': 'getModelRequest',
        'is:valid': "isDataValid",
        'save:all': 'saveAll'
    },
    start(){
        console.log("Starting the facade");
        let deferred = ajax_call(this.url);
        return deferred.then(this.setupModels.bind(this));
    },
    setup(options){
        console.log("Facade.setup");
        console.table(options);
        this.mergeOptions(options, ['edit'])
        this.url = options['context_url'];
    },
    setupModels(context_datas){
        this.datas = context_datas;
        this.models = {};
        this.collections = {};
        this.models.total = new TotalModel();

        var lines = context_datas['lines'];
        this.collections['lines'] = new SupplierInvoiceLineCollection(lines);
        this.collections.attachments = new NodeFileCollection(
            context_datas['attachments']
        );
        this.collections.status_history = new StatusLogEntryCollection(
            context_datas.status_history,
        );
        this.models.supplierInvoice = new SupplierInvoiceModel(context_datas);
        this.setModelUrl('supplierInvoice', AppOption['context_url']);
        this.listenTo(this.models.supplierInvoice, 'saved', this.reloadLines);

        this.computeLineTotal();
    },
    reloadLines(savedData){
        // savedData is null when a global save is performed (save button)
        if (savedData) {
            let savedAttrs = Object.keys(savedData);
            if (savedAttrs.includes('supplier_orders')) {
                let this_ = this;
                this.models.supplierInvoice.fetch().then(function(context_data) {
                    let lines = context_data['lines'];
                    this_.collections['lines'].set(lines);
                });
            }
        }
    },
    computeLineTotal(){
        var collection = this.collections['lines'];

        var datas = {};
        datas['ht'] = collection.total_ht();
        datas['tva'] = collection.total_tva();
        datas['ttc'] = collection.total();
        var channel = this.getChannel();
        this.models.total.set(datas);
        channel.trigger('change:lines');

        // Refresh totals model
        this.computeFundingTotals();
    },

    computeFundingTotals() {
        var invoice = this.models.supplierInvoice;
        var datas = {};
        var ttc = this.models.total.get('ttc');
        // For now, this is unique to invoice
        var caePercentage = invoice.get('cae_percentage');

        datas['ttc_cae'] = getPercent(ttc, caePercentage);
        datas['ttc_worker'] = ttc - datas['ttc_cae'];
        this.models.total.set(datas);
    },
});
const Facade = new FacadeClass();
export default Facade;
